/**
 * Created by user on 2018/4/18.
 */
var fs = require('fs')
var path = require('path')
var count = 0
console.log(JSON.stringify({'name': 'tom'}))
console.log('path', path.join(path.resolve('../logs'), 'file_' + count + '.json'))
const needHost = [
    'm.weibo.cn',
    'passport.weibo.cn'
]
module.exports = {
    *beforeDealHttpsRequest(requestDetail) {
        return true
    },
    *beforeSendRequest(requestDetail) {
        // console.log(requestDetail)
        let accept = requestDetail.requestOptions.headers['Accept'];
        if (accept && accept.indexOf('image') === -1 && checkNeed(requestDetail.requestOptions.hostname)) {
            var _path = requestDetail.requestOptions.hostname + '|request|' + requestDetail.requestOptions.path.replace(/\//g, '|')
            writeFile(JSON.stringify(requestDetail.requestOptions), _path, 'json')
        }
        return null
    },
    *beforeSendResponse(requestDetail, responseDetail) {
        let accept = requestDetail.requestOptions.headers['Accept'];
        if (accept && accept.indexOf('image') === -1 && checkNeed(requestDetail.requestOptions.hostname)) {
            let body = responseDetail.response.body.toString();
            var _path = requestDetail.requestOptions.hostname + '|response|' + requestDetail.requestOptions.path.replace(/\//g, '|')
            writeFile(body, _path, 'json')
        }

        return null
    }
}

function checkNeed(hostname) {
    var need = false
    var reg = new RegExp(hostname)
    for (var i in needHost) {
        if (reg.test(needHost[i])) {
            need = true
            break
        }
    }
    return need
}

function writeFile(data, _path, type) {
    var filename = path.join(path.resolve('../logs'), 'file_' + _path + '.' + type)
    console.log('1', filename)
    fs.appendFile(filename, toUnicode(data), function (err) {
        if (err) {
            console.log("文件写入失败")
        } else {
            console.log("文件追加成功");

        }
    })
}
function toUnicode(s) {
    return s.replace(/([\u4E00-\u9FA5]|[\uFE30-\uFFA0])/g, function () {
        return "\\u" + RegExp["$1"].charCodeAt(0).toString(16);
    });
}
